package cn._2dland.tools;

import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import cn._2dland.utils.HttpUtils;

/** 去除referer */
public class DamnServlet extends HttpServlet {
	private static final long serialVersionUID = 5898390045599937577L;

	private static final String QQ_VIDEO_URL = "http://vtop.qqvideo.tc.qq.com/";
	private static final String SIXROOMS_API_URL = "http://6.cn/v72.php?vid=";
	private static final String FIFTYSIX_API_URL = "http://vxml.56.com/json/";

	public static final String DAMN_API_URL = "https://ssl.acshmily.cn:997/video/damn";

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String videoURL = null;
		try {
			String src = req.getParameter("src");
			String vid = req.getParameter("vid");
			if(src == null || vid == null)
				throw new Exception("无效参数！");
			if("qq".equalsIgnoreCase(src)) {
				videoURL = getQQVideoURL(vid);
			}
			else if("6cn".equalsIgnoreCase(src)) {
				videoURL = get6cnVideoURL(vid);
			}
			else if("56".equals(src)) {
				videoURL = get56VideoURL(vid);
			}
			else {
				throw new Exception("未知视频源！");
			}

			String referer = req.getHeader("Referer");
			if(referer!=null && !referer.matches("http(s)?://\\w+\\.2dland\\.cn/.*"))
				videoURL = getDamnVideoURL();
		}
		catch (Exception e) {
			e.printStackTrace();
			videoURL = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/parse_failed.flv";
		}

		// 跳转到实际地址
		resp.setHeader("Location", videoURL);
		resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
	}

	// 获取QQ视频地址
	private String getQQVideoURL(String vid) throws Exception {
		// 计算tot
		BigInteger tot = BigInteger.valueOf(0);
		BigInteger modder = new BigInteger("4294967296");
		for(int i=0; i<vid.length(); i++){
			int c = vid.charAt(i);
			tot = tot.multiply(BigInteger.valueOf(33)).add(BigInteger.valueOf(c));

			if(tot.compareTo(modder) >= 0){
				tot = tot.remainder(modder);
			}
		}
		// 计算fs
		BigInteger fs = tot.remainder(BigInteger.valueOf(10000 * 10000));
		// 视频地址
		String videoURL = QQ_VIDEO_URL + fs.toString() + "/" + vid + ".flv";
		return videoURL;
	}

	// 获取6cn视频地址
	private String get6cnVideoURL(String vid) throws Exception {
		String sixURL = SIXROOMS_API_URL + vid;
		// 读取远程XML
		Document doc = HttpUtils.getHTTPXMLDocument(sixURL);
		// 获取视频地址
		Element root = doc.getDocumentElement();
		Element video = (Element)root.getElementsByTagName("VIDEO").item(0);
		Element file = (Element)video.getElementsByTagName("file").item(0);
		String videoURL = file.getFirstChild().getNodeValue();
		// 计算key值
		long utcSeconds = System.currentTimeMillis() / 1000;
		utcSeconds += 123456;
		Random rnd = new Random();
		long key1 = 0;
		long key2 = 0;
		long key3 = 1000000000 + rnd.nextInt(1000000000);
		long key4 = 1000000000 + rnd.nextInt(1000000000);
		int keyMode = rnd.nextInt(100);
		if(keyMode > 50) {
			key1 = Math.abs((long)Math.floor(utcSeconds / 3) ^ key3);
			key2 = Math.abs((long)Math.floor(utcSeconds * 2 / 3) ^ key4);
		}
		else {
			key1 = Math.abs((long)Math.floor(utcSeconds * 2 / 3) ^ key3);
			key2 = Math.abs((long)Math.floor(utcSeconds / 3) ^ key4);
		}
		// 拼接URL
		videoURL = new StringBuffer(videoURL)
					.append("?key1=").append(key1)
					.append("&key2=").append(key2)
					.append("&key3=").append(key3)
					.append("&key4=").append(key4)
					.toString();
		return videoURL;
	}

	// 获取56网视频地址
	private String get56VideoURL(String vid) throws Exception {
		String fiftysixURL = FIFTYSIX_API_URL + vid + "/?src=site";
		// 读取远程JSON对象
		JSONObject jsonObj = HttpUtils.getHTTPJSONObject(fiftysixURL);
		// 获取视频地址
		String videoURL = null;
		JSONObject vi = jsonObj.getJSONObject("info");
		JSONArray flvs = vi.getJSONArray("rfiles");
		for(int i=0; i<flvs.length(); i++) {
			JSONObject flv = flvs.getJSONObject(i);
			String type = flv.getString("type");
			if("normal".equals(type))
				videoURL = flv.getString("url");
			else if("clear".equals(type)) {
				videoURL = flv.getString("url");
				break;
			}
		}
		return videoURL;
	}
	
	private String getDamnVideoURL() {
		String[] urls = {
				"http://v38.v.iask.com/f/1/3b1ed0a8144fadc616f58182b28213d211005660.flv",
				"http://d249.v.iask.com/f/1/d864d570cc3aefabfe14f799bef0ac0039107122.flv"
			};
		return urls[1];
	}
}
